package com.aaa.javaweb.servlet;


import com.aaa.javaweb.dao.DeptDao;
import com.aaa.javaweb.dao.impl.DeptDaoImpl;
import com.aaa.javaweb.entity.Dept;
import com.aaa.javaweb.until.TransBean;
import com.alibaba.fastjson.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/queryAllDept")
public class DeptController extends HttpServlet {
    DeptDao deptDao=new DeptDaoImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String method = req.getParameter("method");
        if(method!=null){
            switch (method){
                case "del":
                    del(req,resp);
                    break;
                case "add":
                    add(req,resp);
                    break;
                case "upd":
                    upd(req,resp);
                    break;
            }
        }else{
            List<Map> maps=deptDao.queryAll();
            Map m = new HashMap();
            m.put("code",0);
            m.put("msg","");
            m.put("count",maps.size());
            m.put("data",maps);
            String map= JSON.toJSONString(m);
            PrintWriter out = resp.getWriter();
            out.print(map);
            out.flush();
            out.close();
        }
    }

    private void upd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String id = req.getParameter("id");
        Map map=deptDao.findGustById(id);
        req.setAttribute("upd",map);
        req.getRequestDispatcher("add.jsp").forward(req,resp);
    }

    private void del(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String gid = req.getParameter("id");
        //dao   删除
        int i= deptDao.delGust(gid);
        if(i>0){
            //
            resp.sendRedirect("user/showDept.jsp");
        }
    }
    private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Map<String, String[]> parameterMap = req.getParameterMap();
        Dept g=new Dept();
        TransBean.populate(g,parameterMap);
        int i=deptDao.add(g);
        //
        resp.sendRedirect("queryAllDept");
    }
}
